// WebSocketService.ts
// import Vue from 'vue';
import config from '@/config';

interface Message {
	msg : string;
	type : string;
}

const socket = {
	isConnected: false,
	unread: 10,
	
	close(){
		uni.closeSocket({})
	},

	connect(fun ?: Function) {
		if (!this.isConnected) {
			uni.connectSocket({
				url: config.WORKERMAN_URL,
			});

			uni.onSocketOpen(() => {
				console.log('WebSocket connected');
				this.isConnected = true;
			});

			uni.onSocketClose(() => {
				console.log('WebSocket closed');
				this.isConnected = false;
			});

			uni.onSocketError((error : any) => {
				console.error(`WebSocket error: ${error}`);
			});

			uni.onSocketMessage((res : any) => {
				const message : Message = JSON.parse(res.data);
				console.log(message)

				// 根据当前路由判断是否需要弹出提示
				const pages = getCurrentPages();
				const currentPage = pages[pages.length - 1];
				console.log(currentPage.route)
				if (
					currentPage.route == 'pages/chat-list/chat-list' ||
					currentPage.route == 'pages/chat/chat'
				) {
					console.log('单独处理')
					if (typeof fun == 'function') {
						fun(message)
					}
				} else {
					if (message.type == 'chat') {
						uni.showToast({
							title: message.msg,
							icon: 'none',
						});
					}
				}
			});
		}
	},

	// 发送消息的函数
	sendMessage(message : Object) {
		console.log(message)
		if (this.isConnected) {
			const data = JSON.stringify(message);
			uni.sendSocketMessage({
				data,
			});
		} else {
			console.error('WebSocket is not connected. Message not sent.');
		}
	},
};

export default socket;